package com.cloudinnov.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.JarURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.model.EquipmentPoints;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.model.RealTimeData;
import com.easemob.server.example.api.ChatGroupAPI;
import com.easemob.server.example.api.IMUserAPI;
import com.easemob.server.example.api.SendMessageAPI;
import com.easemob.server.example.comm.ClientContext;
import com.easemob.server.example.comm.EasemobRestAPIFactory;
import com.easemob.server.example.comm.body.ChatGroupBody;
import com.easemob.server.example.comm.body.IMUserBody;
import com.easemob.server.example.comm.body.ImgMessageBody;
import com.easemob.server.example.comm.body.ResetPasswordBody;
import com.easemob.server.example.comm.body.TextMessageBody;
import com.easemob.server.example.comm.body.UserNamesBody;
import com.easemob.server.example.comm.wrapper.ResponseWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.xiaomi.xmpush.server.Constants;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;
import com.xiaomi.xmpush.server.TargetedMessage;

/**
 * @author guochao
 * @date 2016年2月26日下午6:15:00
 * @email chaoguo@cloudinnov.com
 * @remark 通用工具类
 * @version
 */
/**
 * @author guochao
 * @date 2016年2月26日下午6:15:11
 * @email chaoguo@cloudinnov.com
 * @remark
 * @version
 */
public class CommonUtils {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);
    public static final String SPLIT_CLICK = ".";
    public static final String SPLIT_COMMA = ",";
    public static final String SPLIT_LINE = "_";
    public static final String SPLIT_VERTICAL_LINE = "|";
    public static final String SPLIT_SEMICOLON = ";";// semicolon
    public static final String LEFT_BRACKETS = "(";
    public static final String RIGHT_BRACKETS = ")";
    public static String ENV = "dev";
    public static final int STATUS_NORMAL = 1;
    public static final int STATUS_DELETE = 9;
    public static final int STATUS_INTERDIT = 0;
    public static final int STATUS_EXCEPTION = -1;
    public static final String STATUS_NORMAL_MSG = "正常";
    public static final String STATUS_DELETE_MSG = "删除";
    public static final String STATUS_INTERDIT_MSG = "禁用";
    public static final int IS_RECEIVE_ORDER_YES = 1;// 可接单
    public static final int IS_RECEIVE_ORDER_NO = 2;// 不可接单
    public static final int IS_INVATATION_ORDER_YES = 1;// 可邀请
    public static final int IS_INVATATION_ORDER_NO = 2;// 不可邀请
    public static final int IS_CANCLE_ORDER_YES = 1;// 可关闭
    public static final int IS_CANCLE_ORDER_NO = 2;// 不可关闭
    public static final int IS_TURN_ORDER_YES = 1;// 可转派
    public static final int IS_TURN_ORDER_NO = 2;// 不可转派
    public static final int ALARM_ROLE_PADDING = 1;// 工单责任人
    public static final int ALARM_ROLE_PARTIN = 2;// 工单参与者
    // 处理状态
    public static final int ORDER_STATUS_NEW = 0;// 未解决，可接单
    public static final int ORDER_STATUS_HANDLE = 1;
    public static final int ORDER_STATUS_CLOSE = 2;
    public static final int ALARM_WORK_IGNORE = 1;
    public static final int ALARM_WORK_NOT_IGNORE = 2;
    // 解决工单状态
    public static final int OPERATION_HANDLE = 1;
    // 未解决工单状态
    public static final int OPERATION_NOTRESOLVER = 2;
    // 转派状态
    public static final int OPERATION_TURN_TOSEND = 3;
    // 忽略状态
    public static final int OPERATION_IGNORE = 4;
    public static final int WORK_RESULT_NEW = 0;
    public static final int WORK_RESULT_CLOSE = 1;
    // 处理状态翻译
    public static final String WORK_RESULT_NEW_MSG = "未解决";
    public static final String WORK_RESULT_CLOSE_MSG = "已解决";
    // 处理状态翻译
    public static final String ORDER_STATUS_NEW_MSG = "未处理";
    public static final String ORDER_STATUS_HANDLE_MSG = "处理中";
    public static final String ORDER_STATUS_CLOSE_MSG = "已处理";
    public static final int DEFAULT_NUM = 0;
    public static final int SUCCESS_NUM = 1;
    public static final String SUCCESS_MSG = "success";
    public static final int ERROR_NUM = 0;
    public static final String ERROR_MSG = "error";
    public static final String CAREMA_OK = "OK";
    public static final String CAREMA_NOT_FOUND = "NOT FOUND";
    public static final int CAREMA_OK_CODE = 200;
    public static final int CAREMA_NOT_FOUND_CODE = 404;
    /**
     * 模拟量前台type
     */
    public static final String POINT_TYPE_MN = "mn";
    /**
     * 数字量前台type
     */
    public static final String POINT_TYPE_SZ = "sz";
    /**
     * 模拟量
     */
    public static final String ANALOG_QUANTITY = "A";
    /**
     * 模拟量MSG
     */
    public static final String ANALOG_QUANTITY_MSG = "模拟量";
    /**
     * 开关量
     */
    public static final String DIGITAL_QUANTITY = "D";
    /**
     * 开关量MSG
     */
    public static final String DIGITAL_QUANTITY_MSG = "开关量";
    /**
     * 故障通道
     */
    public static final String FAULT_QUANTITY = "F";
    /* 离线 */
    public static final int EQU_STATE_OFFLINE = 0;
    /* 停机 */
    public static final int EQU_STATE_NO_SET_PARAME = 1;
    /* 故障 */
    public static final int EQU_STATE_FAULT = 2;
    /* 正常 */
    public static final int EQU_STATE_NORMAL = 3;
    public static final Integer OTHER_EXCEPTION_CODE = 1000;
    public static final Integer SYSTEM_EXCEPTION_CODE = 1001;
    public static final Integer PARAMETER_EXCEPTION_CODE = 1002;
    public static final Integer NUMBERFORMAT_EXCEPTION_CODE = 1003;
    public static final String OTHER_EXCEPTION_MSG = "其他异常";
    public static final String SYSTEM_EXCEPTION_MSG = "系统异常";
    public static final String PARAMETER_EXCEPTION_MSG = "参数异常";
    public static final String NUMBERFORMAT_EXCEPTION_MSG = "数据类型错误";
    public static final String REQUEST_LANGUAGE = "language";
    public static final int RANGE_EQU_TYPE = 2;
    public static final int RANGE_LINE_TYPE = 1;
    public static final int ISCRUCIAL_POINT_YES = 1;
    public static final int ISCRUCIAL_POINT_NO = 2;
    public static String LOGIN_LANGUAGE = "cn";
    public static String OEM_TYPE = "oem";
    public static String INTEGRATOR_TYPE = "integrator";
    public static String CUSTORER_TYPE = "customer";
    public static String AGENT_TYPE = "agent";
    public static String ADMIN_TYPE = "admin";
    public static final int PORTAL_ADMIN_TYPE = 1;
    public static final int PORTAL_OEM_TYPE = 2;
    public static final int PORTAL_AGENT_TYPE = 3;
    public static final int PORTAL_CUSTOMER_TYPE = 4;
    public static String LOGIN_ADMIN_TYPE = "admin";
    public static String LOGIN_CUSTORER_TYPE = "user";
    public static final String WEB_ADDRESS = PropertiesUtils.findPropertiesKey("website.address");
    public static final String IMAGE_DEFAULT_PUBLIC = PropertiesUtils.findPropertiesKey("image.default.public");
    public static final String IMAGE_DEFAULT_USER = PropertiesUtils.findPropertiesKey("image.default.user");
    public static final String WEB_ADDRESS_FRONTEND_USER = PropertiesUtils
            .findPropertiesKey("website.address.frontend.user");
    public final static String WINDOWS_UPLOAD_IMG_PATH = PropertiesUtils.findPropertiesKey("upload.windows.path");
    public final static String LINUX_UPLOAD_IMG_PATH = PropertiesUtils.findPropertiesKey("upload.linux.path");
    public final static String UPLOAD_IMG_PATH = "upload";
    public final static String POINT_UPLOAD_PATH = "point";
    public static final String CI_PRODUCT_BOM = PropertiesUtils.findPropertiesKey("ci.product.bom");
    public static final String APP_KEY = PropertiesUtils.findPropertiesKey("appkey");
    public static final String APP_MASTER_SECRET = PropertiesUtils.findPropertiesKey("appmastersecret");
    public static final String APP_PACKAGE = PropertiesUtils.findPropertiesKey("apppackage");
    private static final String baiduServerURL = PropertiesUtils.findPropertiesKey("baidu.server.url");
    private static final String baiduApiKey = PropertiesUtils.findPropertiesKey("baidu.api.key");
    private static final String baiduSecretKey = PropertiesUtils.findPropertiesKey("baidu.secret.key");
    public static final String KAFKA_REAL_TOPIC = PropertiesUtils.findPropertiesKey("kafka.real.topic");
    public static final String KAFKA_FAULT_TOPIC = PropertiesUtils.findPropertiesKey("kafka.fault.topic");
    public static final String CMS_URL = PropertiesUtils.findPropertiesKey("cms.url");
    public static final String CMS_SWITCH_URL = PropertiesUtils.findPropertiesKey("cms.swith");
    public static final String CMS_SCREEN_URL = PropertiesUtils.findPropertiesKey("cms.screen");
    public static final String CMS_TVMALL = PropertiesUtils.findPropertiesKey("cms.tvwall");
    // 穿云配置项名称
    public static final String TRANSCLOUD_CONFIG_NAME = "transcloud";
    // 初始化数据库配置项名称
    public static final String INITDB_CONFIG_NAME = "initdb";
    public static final int SECONDS_TYPE = 1;
    public static final int MINUTES_TYPE = 2;
    public static final int HOUR_TYPE = 3;
    // 默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;
    public static final int FAULT_IS_CERATE_ORDER_YES = 1;// 产生工单
    public static final int FAULT_IS_CERATE_ORDER_NO = 2;// 不产生工单
    public static final int FAULT_TYPE_ALARM = 1;// 故障码类型 --告警
    public static final int FAULT_TYPE_FAULT = 2;// 故障码类型 --故障
    public static final int FAULT_LEVEL_SERIOUS = 1;// 故障码等级：严重
    public static final int FAULT_TYPE_URGENT = 2;// 故障码等级：紧急
    public static final int FAULT_TYPE_COMMONLY = 3;// 故障码等级：一般
    public static final int REDIS_POINT_VALUEDB = Integer
            .parseInt(PropertiesUtils.findPropertiesKey("redis.db.pointvalue"));
    public static final int REDIS_FAULT_VALUEDB = Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.fault"));
    public static final int REDIS_LOGIN_VALUEDB = Integer
            .parseInt(PropertiesUtils.findPropertiesKey("redis.db.login"));;
    public static final int REDIS_CODE_VALUEDB = Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.code"));
    public static final int REDIS_CATASTAT_VALUEDB = Integer
            .parseInt(PropertiesUtils.findPropertiesKey("redis.db.catastat"));
    public static final int REDIS_RECORD_VALUEDB = Integer
            .parseInt(PropertiesUtils.findPropertiesKey("redis.db.record"));
    public static final int REDIS_STATE_VALUEDB = Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.state"));
    public static final String QR_EQUIPMENT = "equipment";
    public static final int ROLE_TYPE_SYSTEM = 1;
    public static final int ROLE_TYPE_CUSTOM = 2;
    public static final int ROLE_DELETE_NO = 1;
    public static final int ROLE_DELETE_YES = 1;
    public static final int FAULT_TRANS_GENERAL = 1;
    public static final int FAULT_TRANS_CUSTOMER = 2;
    public static final int MSG_TEXT_TYPE = 1;
    public static final int MSG_IMAGE_TYPE = 2;
    public static final int MSG_VIDEO_TYPE = 3;
    public static final int MSG_VOICE_TYPE = 4;
    public static final String LOGIN_TYPE_APP = "app";
    public static final String LOGIN_TYPE_WEB = "web";
    public static final int PUSH_MSG_TYPE_REMOTE = 1;
    public static final int PUSH_MSG_TYPE_ALARM_NEW = 2;
    public static final int UPLOAD_TYPE_MSG_TEXT = 1;
    public static final int UPLOAD_TYPE_MSG_IMAGE = 2;
    public static final int UPLOAD_TYPE_MSG_VOICE = 3;
    public static final int UPLOAD_TYPE_MSG_VIDEO = 4;
    public static final String UPLOAD_TYPE_MSG_TEXT_STR = "text";
    public static final String UPLOAD_TYPE_MSG_IMAGE_STR = "image";
    public static final String UPLOAD_TYPE_MSG_VOICE_STR = "voice";
    public static final String UPLOAD_TYPE_MSG_VIDEO_STR = "video";
    public static final int WORKLOG_TYPE_MSG_TEXT = 1;
    public static final int WORKLOG_TYPE_MSG_IMAGE = 2;
    public static final int WORKLOG_TYPE_MSG_VOICE = 3;
    public static final int WORKLOG_TYPE_MSG_VIDEO = 4;
    public static final String ROLE_NAME_ENGINEER = "工程师";
    public static final int POINT_VIEW_TYPE_PANEL = 1;
    public static final int POINT_VIEW_TYPE_BOARD = 2;
    public static final int POINT_VIEW_TYPE_REALTIME_CURVE = 3;
    public static final int POINT_VIEW_TYPE_BOARD_AND_REALTIME_CURVE = 4;
    public static final int RESOURCE_PARENT_ID = 0;
    /* 触发器类型 */
    public static final int TRIGGER_TYPE_DAY = 1;
    public static final int TRIGGER_TYPE_WEEK = 2;
    public static final int TRIGGER_TYPE_MONTH = 3;
    public static final int TRIGGER_TYPE_YEAR = 4;
    /* 群控方案类型 */
    public static final int CONTROL_SOLUTION_BOARD_TYPE = 1;// 情报板
    public static final int CONTROL_SOLUTION_DEVICE_TYPE = 2;// 其他设备
    /* 进行控制的设备分类下的设备 */
    public static final String CONTROLLER_EQUIPMENTS_LAMP = "DNZM";// 照明灯
    public static final String CONTROLLER_EQUIPMENTS_FAN = "SDFJ";// 隧道风机
    public static final String CONTROLLER_EQUIPMENTS_MARKER = "CDZSQ";// 车道指示器
    public static final String CONTROLLER_EQUIPMENTS_TRAFFIC = "JTXHD";// 交通信号灯
    public static final String CONTROLLER_EQUIPMENTS_ROLLER = "HDJIM";// 横洞卷帘门
    /* 设备控制的指标类型 */
    public static final String EQUIPMENTS_INDEXTYPE_ONOFF = "ONOFF";// 设备控制指标--开
    public static final String EQUIPMENTS_INDEXTYPE_ON = "ON";// 设备控制指标--关
    public static final String EQUIPMENTS_INDEXTYPE_JUST_GREEN = "JUST_GREEN";// 设备控制指标--正绿
    public static final String EQUIPMENTS_INDEXTYPE_JUST_RED = "JUST_RED";// 设备控制指标--正红
    public static final String EQUIPMENTS_INDEXTYPE_BACK_RED = "BACK_RED";// 设备控制指标--反红
    public static final String EQUIPMENTS_INDEXTYPE_BACK_GREEN = "BACK_GREEN";// 设备控制指标--反绿
    public static final String EQUIPMENTS_INDEXTYPE_HL = "HL";// 设备控制指标--黄灯
    public static final String EQUIPMENTS_INDEXTYPE_LEFT = "LEFT";// 设备控制指标--左转
    public static final String EQUIPMENTS_INDEXTYPE_HR = "HR";// 设备控制指标--红灯
    public static final String EQUIPMENTS_INDEXTYPE_HG = "HG";// 设备控制指标--绿灯
    public static final String EQUIPMENTS_INDEXTYPE_FORWARD = "FORWARD";// 设备控制指标--正转
    public static final String EQUIPMENTS_INDEXTYPE_REVERSAL = "REVERSAL";// 设备控制指标--反转
    public static final String EQUIPMENTS_INDEXTYPE_STOP = "STOP";// 设备控制指标--停止
    public static final String EQUIPMENTS_INDEXTYPE_RISE = "RISE";// 设备控制指标--上升
    public static final String EQUIPMENTS_INDEXTYPE_DECLINE = "DECLINE";// 设备控制指标--下降
    public static final String EQUIPMENTS_INDEXTYPE_HD_ONOFF = "HD_ONOFF";// 设备控制指标--横洞指示器开
    public static final String EQUIPMENTS_INDEXTYPE_VI = "VI";// VI检测器指标类型
    public static final String EQUIPMENTS_INDEXTYPE_CO = "CO";// CO检测器指标类型
    public static final String EQUIPMENTS_INDEXTYPE_NO2 = "NO2";// NO2检测器指标类型
    public static final String EQUIPMENTS_INDEXTYPE_WIND_SPEED = "WIND_SPEED";// 风速/风向检测器指标类型
    public static final String EQUIPMENTS_INDEXTYPE_ILLUMINATION = "ILLUMINATION";// 洞内光强模拟量输入
                                                                                  // 照度指标类型
    public static final String EQUIPMENTS_INDEXTYPE_LIGHT_INTENSITY = "LIGHT_INTENSITY";// 光强模拟量输入洞外
                                                                                        // 光强指标类型
    /* 前端控制命令指标 */
    public static final String EQUIPMENTS_JUST = "just";// 前端设备控制命令--正面
    public static final String EQUIPMENTS_BACK = "back";// 前端设备控制命令--反面面
    /* 点位值 */
    public static final int INDEX_TYPE_OF = 1;// 设备控制--打开
    public static final int INDEX_TYPE_ON = 0;// 设备控制--关闭
    /* 路段类型 */
    public static final String SECTION_TYPE_TUNNEL = "tunnel";// 设备控制--关闭
    public static final int FEEDBACK_NO = 1;// 控制点
    public static final int FEEDBACK_YES = 2;// 反馈点
    public static Map<String, List<EquipmentsAttr>> CACHE_EQUIPMENT_ATTRS_MAP = new ConcurrentHashMap<>();// 隧道设备状态推送-设备附加属性缓存
    public static Map<String, List<EquipmentPoints>> CACHE_EQUIPMENT_POINTS_MAP = new ConcurrentHashMap<>();// 隧道设备状态推送-设备点位缓存
    public static long LAST_VISIT_TIME = 0;// 隧道设备状态推送-最后数据更新时间

    public static Map<String, Object>ControlSolutionCacheMap = null;
    
    public static Map<String, Object>COLLECT_DATA_MAP=new ConcurrentHashMap<>();//数据搜集缓存
    
    /**
     * getUUID
     * @Description: 获取uuid
     * @param @return 参数
     * @return String 返回类型
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
    /**
     * MD5
     * @Description: MD5加密
     * @param @param res
     * @param @return 参数
     * @return String 返回类型
     */
    public static String MD5(String res) {
        return DigestUtils.md5Hex(res);
    }
    /**
     * convertSourData
     * @Description: string 转 double
     * @param @param dataStr
     * @param @return
     * @param @throws Exception 参数
     * @return double 返回类型
     */
    public static double convertSourData(String dataStr) throws Exception {
        if (dataStr != null && !"".equals(dataStr)) {
            return Double.valueOf(dataStr);
        }
        throw new NumberFormatException("convert error!");
    }
    /**
     * isEmpty
     * @Description: 判断变量是否为空
     * @param @param s
     * @param @return 参数
     * @return boolean 返回类型
     */
    public static boolean isEmpty(String s) {
        if (null == s || "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * isNotEmpty
     * @Description: 判断变量是否为空
     * @param @param s
     * @param @return 参数
     * @return boolean 返回类型
     */
    public static boolean isNotEmpty(String s) {
        if (null == s || "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s)) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * fromUsage
     * @Description: 使用率计算
     * @param @param free
     * @param @param total
     * @param @return 参数
     * @return String 返回类型
     */
    public static String fromUsage(long free, long total) {
        Double d = new BigDecimal(free * 100 / total).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(d);
    }
    /**
     * formatDouble
     * @Description: 保留两位小数
     * @param @param b
     * @param @return 参数
     * @return String 返回类型
     */
    public static String formatDouble(Double b) {
        BigDecimal bg = new BigDecimal(b);
        return bg.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }
    /**
     * fromDateH
     * @Description: 返回当前时间 格式：yyyy-MM-dd hh:mm:ss
     * @param @return 参数
     * @return String 返回类型
     */
    public static String fromDateH() {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format1.format(new Date());
    }
    /**
     * 日期格式字符串转换成时间戳
     * @param date 字符串日期
     * @param format 如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String date2TimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @param formatStr
     * @return
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty())
            format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        if (seconds.length() == 10) {
            date = new Date(Long.valueOf(seconds + "000"));
        } else if (seconds.length() == 13) {
            date = new Date(Long.valueOf(seconds));
        }
        return sdf.format(date);
    }
    /**
     * 实时值时间转换
     * @param seconds
     * @return
     */
    public static Date timeStampToDate(String seconds) {
        Date date = null;
        if (seconds.length() == 10) {
            date = new Date(Long.parseLong(seconds) * 1000);
        } else if (seconds.length() == 13) {
            date = new Date(Long.parseLong(seconds));
        }
        return date;
    }
    /**
     * 实时值时间转换
     * @param seconds
     * @return
     */
    public static Date timeStampToDate(long seconds) {
        Date date = null;
        if (seconds / 10 == 0) {
            date = new Date(seconds * 1000);
        } else {
            date = new Date(seconds);
        }
        return date;
    }
    /**
     * 实时值时间统一返回10位时间戳
     * @param seconds
     * @return
     */
    public static String timeStampSubStringTen(String seconds) {
        String time = null;
        if (seconds.length() == 10) {
            time = seconds;
        } else if (seconds.length() == 13) {
            time = String.valueOf((Long.parseLong(seconds) / 1000));
        }
        return time;
    }
    /**
     * 此部分会引起spring cglib代理失败 出现NotRefClass错误
     */
    // static {
    // Properties pro = PropertiesUtils.getProperties();
    // getInputHtmlUTF8(pro.getProperty(EN_NAME) + pro.getProperty(ZH_NAME)
    // + pro.getProperty(ZB_NAME));
    // }
    /**
     * fromDateY
     * @Description: 返回当前时间 格式：yyyy-MM-dd
     * @param @return 参数
     * @return String 返回类型
     */
    public static String fromDateY() {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        return format1.format(new Date());
    }
    /**
     * 把毫秒级时间转换为格式化后的时间格式
     * @param str 需要转换的毫秒
     * @return yyyyMMddHHmmss
     */
    public static String dateFormatYYYYMMddHH(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHH");
        String date = sdf.format(new Date(time * 1000));
        return date;
    }
    /**
     * removeSameItem
     * @Description: 用来去掉List中空值和相同项的。
     * @param @param list
     * @param @return 参数
     * @return List<String> 返回类型
     */
    public static List<String> removeSameItem(List<String> list) {
        List<String> difList = new ArrayList<String>();
        for (String t : list) {
            if (t != null && !difList.contains(t)) {
                difList.add(t);
            }
        }
        return difList;
    }
    /**
     * toIpAddr
     * @Description: 返回用户的IP地址
     * @param @param request
     * @param @return 参数
     * @return String 返回类型
     */
    public static String toIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equalsIgnoreCase("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        return ip;
    }
    /**
     * 传入原图名称，，获得一个以时间格式的新名称
     * @param fileName 原图名称
     * @return
     */
    public static String generateFileName(String fileName) {
        Date nowDate = new Date();
        String cate = new SimpleDateFormat("yyyyMM").format(nowDate);
        String path = null;
        if (fileName == null) {
            path = WEB_ADDRESS + "/" + UPLOAD_IMG_PATH + "/" + cate + "/" + CommonUtils.getUUID() + ".png";
        } else {
            path = WEB_ADDRESS + "/" + UPLOAD_IMG_PATH + "/" + cate + "/" + fileName + ".png";
        }
        return path;
    }
    /**
     * 取得html网页内容 UTF8编码
     * @param urlStr 网络地址
     * @return String
     */
    public static String getInputHtmlUTF8(String urlStr) {
        URL url = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
            httpsURLConnection.setRequestMethod("GET");
            httpsURLConnection.setConnectTimeout(5 * 1000);
            httpsURLConnection.connect();
            if (httpsURLConnection.getResponseCode() == 200) {
                // 通过输入流获取网络图片
                InputStream inputStream = httpsURLConnection.getInputStream();
                String data = readHtml(inputStream, "UTF-8");
                inputStream.close();
                return data;
            }
        } catch (Exception e) {
            // e.printStackTrace();
            return null;
        }
        return null;
    }
    /**
     * 取得html网页内容 GBK编码
     * @param urlStr 网络地址
     * @return String
     */
    public static String getInputHtmlGBK(String urlStr) {
        URL url = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
            httpsURLConnection.setRequestMethod("GET");
            httpsURLConnection.setConnectTimeout(5 * 1000);
            httpsURLConnection.connect();
            if (httpsURLConnection.getResponseCode() == 200) {
                // 通过输入流获取网络图片
                InputStream inputStream = httpsURLConnection.getInputStream();
                String data = readHtml(inputStream, "GBK");
                inputStream.close();
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
    /**
     * @param inputStream
     * @param uncode 编码 GBK 或 UTF-8
     * @return
     * @throws Exception
     */
    public static String readHtml(InputStream inputStream, String uncode) throws Exception {
        InputStreamReader input = new InputStreamReader(inputStream, uncode);
        BufferedReader bufReader = new BufferedReader(input);
        String line = "";
        StringBuilder contentBuf = new StringBuilder();
        while ((line = bufReader.readLine()) != null) {
            contentBuf.append(line);
        }
        return contentBuf.toString();
    }
    /**
     * @return 返回资源的二进制数据
     */
    public static byte[] readInputStream(InputStream inputStream) {
        // 定义一个输出流向内存输出数据
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 定义一个缓冲区
        byte[] buffer = new byte[1024];
        // 读取数据长度
        int len = 0;
        // 当取得完数据后会返回一个-1
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // 把缓冲区的数据 写到输出流里面
                byteArrayOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 得到数据后返回
        return byteArrayOutputStream.toByteArray();
    }
    /**
     * 修改配置
     * @param request
     * @param nodeId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/modifySer")
    public static Map<String, Object> modifySer(String key, String value) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            PropertiesUtils.modifyProperties(key, value);
        } catch (Exception e) {
            dataMap.put("flag", false);
        }
        dataMap.put("flag", true);
        return dataMap;
    }
    /**
     * 获取登录账号的ID
     * @param request
     * @return
     */
    public static String findUserSessionId(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute("userSessionId");
        if (obj != null) {
            return obj.toString();
        }
        return null;
    }
    /**
     * 获取登录账号的的对象 * @param request
     * @return Object 返回是Object..需要转型为(Account)Object
     */
    public static AuthUsers findUserSession(HttpServletRequest request) {
        return (AuthUsers) request.getSession(false).getAttribute("login");
    }
    /**
     * 获取登录账号的的对象 * @param request
     * @return Object 返回是Object..需要转型为(Account)Object
     */
    public static String getLanguage(HttpServletRequest request) {
        if (request.getRequestURI().indexOf("logindo") != -1) {
            LOGIN_LANGUAGE = request.getParameter(REQUEST_LANGUAGE);
        }
        return LOGIN_LANGUAGE;
    }
    /**
     * 提供精确的减法运算。
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }
    /**
     * 提供精确的加法运算。
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    /**
     * 提供精确的乘法运算。
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }
    /**
     * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到 小数点以后10位，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @return 两个参数的商
     */
    public static double div(double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }
    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /**
     * 去除字符串最后一个逗号,若传入为空则返回空字符串
     * @descript
     * @param para
     * @return
     * @date 2015年3月29日
     * @version 1.0
     */
    public static String trimComma(String para) {
        if (StringUtils.isNotBlank(para)) {
            if (para.endsWith(",")) {
                return para.substring(0, para.length() - 1);
            } else {
                return para;
            }
        } else {
            return "";
        }
    }
    /**
     * 将Map形式的键值对中的值转换为泛型形参给出的类中的属性值 t一般代表pojo类
     * @descript
     * @param t
     * @param params
     * @date 2015年3月29日
     * @version 1.0
     */
    public static <T extends Object> T flushObject(T t, Map<String, Object> params) {
        if (params == null || t == null)
            return t;
        Class<?> clazz = t.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                Field[] fields = clazz.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    String name = fields[i].getName(); // 获取属性的名字
                    Object value = params.get(name);
                    if (value != null && !"".equals(value)) {
                        // 注意下面这句，不设置true的话，不能修改private类型变量的值
                        fields[i].setAccessible(true);
                        fields[i].set(t, value);
                    }
                }
            } catch (Exception e) {
            }
        }
        return t;
    }
    /**
     * html转议
     * @descript
     * @param content
     * @return
     * @date 2015年4月27日
     * @version 1.0
     */
    public static String htmltoString(String content) {
        if (content == null)
            return "";
        String html = content;
        html = html.replace("'", "&apos;");
        html = html.replaceAll("&", "&amp;");
        html = html.replace("\"", "&quot;"); // "
        html = html.replace("\t", "&nbsp;&nbsp;");// 替换跳格
        html = html.replace(" ", "&nbsp;");// 替换空格
        html = html.replace("<", "&lt;");
        html = html.replaceAll(">", "&gt;");
        return html;
    }
    /**
     * html转议
     * @descript
     * @param content
     * @return
     * @date 2015年4月27日
     * @version 1.0
     */
    public static String stringtohtml(String content) {
        if (content == null)
            return "";
        String html = content;
        html = html.replace("&apos;", "'");
        html = html.replaceAll("&amp;", "&");
        html = html.replace("&quot;", "\""); // "
        html = html.replace("&nbsp;&nbsp;", "\t");// 替换跳格
        html = html.replace("&nbsp;", " ");// 替换空格
        html = html.replace("&lt;", "<");
        html = html.replaceAll("&gt;", ">");
        return html;
    }
    /**
     * 是否为整数
     * @param str
     * @return
     */
    public static boolean isNumeric1(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    /**
     * 通过redis中的value来转换为RealTimeData获取实时值 getPointValueTime
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param pointValue
     * @param @return 参数
     * @return RealTimeData 返回类型
     */
    public static RealTimeData getPointValueTime(String pointValue) {
        if (pointValue == null) {
            return null;
        }
        String value = pointValue.split(",")[1];
        long time = 0L;
        if (pointValue.split(",")[0].length() == 10) {
            time = Long.parseLong(pointValue.split(",")[0] + "000");
        } else {
            time = Long.parseLong(pointValue.split(",")[0]);
        }
        return new RealTimeData(value, time);
    }
    /**
     * 计算时间差 computeTime
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param time 时间戳
     * @param @param type SECONDS_TYPE MINUTES_TYPE HOUR_TYPE
     * @param @return 参数
     * @return long 返回类型
     */
    public static long computeTime(long time, int type) {
        switch (type) {
            case SECONDS_TYPE:
                return (System.currentTimeMillis() - time) / 1000;
            case MINUTES_TYPE:
                return (System.currentTimeMillis() - time) / 1000 / 60;
            case HOUR_TYPE:
                return (System.currentTimeMillis() - time) / 1000 / 3600;
            default:
                return (System.currentTimeMillis() - time) / 1000;
        }
    }
    /**
     * 从包package中获取所有的Class
     * @param pack
     * @return
     */
    public static Set<Class<?>> getClasses(String pack) {
        // 第一个class类的集合
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
        // 是否循环迭代
        boolean recursive = true;
        // 获取包的名字 并进行替换
        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');
        // 定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    // System.err.println("file类型的扫描");
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                } else if ("jar".equals(protocol)) {
                    // 如果是jar包文件
                    // 定义一个JarFile
                    // System.err.println("jar类型的扫描");
                    JarFile jar;
                    try {
                        // 获取jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        // 从此jar包 得到一个枚举类
                        Enumeration<JarEntry> entries = jar.entries();
                        // 同样的进行循环迭代
                        while (entries.hasMoreElements()) {
                            // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            // 如果是以/开头的
                            if (name.charAt(0) == '/') {
                                // 获取后面的字符串
                                name = name.substring(1);
                            }
                            // 如果前半部分和定义的包名相同
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                // 如果以"/"结尾 是一个包
                                if (idx != -1) {
                                    // 获取包名 把"/"替换成"."
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                // 如果可以迭代下去 并且是一个包
                                if ((idx != -1) || recursive) {
                                    // 如果是一个.class文件 而且不是目录
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        // 去掉后面的".class" 获取真正的类名
                                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                                        try {
                                            // 添加到classes
                                            classes.add(Class.forName(packageName + '.' + className));
                                        } catch (ClassNotFoundException e) {
                                            // log
                                            // .error("添加用户自定义视图类错误
                                            // 找不到此类的.class文件");
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        // log.error("在扫描用户定义视图时从jar包获取文件出错");
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classes;
    }
    /**
     * 以文件的形式来获取包下的所有Class
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
            Set<Class<?>> classes) {
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            // log.warn("用户定义包名 " + packageName + " 下没有任何文件");
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles(new FileFilter() {
            // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });
        // 循环所有文件
        for (File file : dirfiles) {
            // 如果是目录 则继续扫描
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                // 如果是java类文件 去掉后面的.class 只留下类名
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    // 添加到集合中去
                    // classes.add(Class.forName(packageName + '.' +
                    // className));
                    // 这里用forName有一些不好，会触发static方法，没有使用classLoader的load干净
                    classes.add(
                            Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    // log.error("添加用户自定义视图类错误 找不到此类的.class文件");
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 一个String字符串转换为json格式
     * @descript
     * @param s
     * @return
     * @author lijianning
     * @date 2015年6月15日
     * @version 1.0v
     */
    public static String stringToJson(String s) {
        if (s == null) {
            return nullToJson();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                default:
                    if (ch >= '\u0000' && ch <= '\u001F') {
                        String ss = Integer.toHexString(ch);
                        sb.append("\\u");
                        for (int k = 0; k < 4 - ss.length(); k++) {
                            sb.append('0');
                        }
                        sb.append(ss.toUpperCase());
                    } else {
                        sb.append(ch);
                    }
            }
        }
        return sb.toString();
    }
    public static String nullToJson() {
        return "";
    }
    /**
     * string字符串保留2位小数 strFormatTwoDecimal
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param arg
     * @param @return 参数
     * @return String 返回类型
     */
    public static String strFormatTwoDecimal(String arg) {
        try {
            DecimalFormat format = new DecimalFormat("0.00");
            return format.format(new BigDecimal(arg));
        } catch (Exception e) {
            System.out.println("strFormatTwoDecimal,Data:" + arg);
            return arg;
        }
    }
    public static void exportToFile(String fileName, String data) {
        if (fileName == null || data == null) {
            logger.debug("data is null \t" + data);
            return;
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            byte[] content = data.getBytes();
            // 判断文件夹是否存在，不存在则建立文件夹
            // windows下
            File file = null;
            if ("\\".equals(File.separator)) {
                file = new File(WINDOWS_UPLOAD_IMG_PATH + File.separator + POINT_UPLOAD_PATH);
            }
            // linux下
            if ("/".equals(File.separator)) {
                file = new File(LINUX_UPLOAD_IMG_PATH + File.separator + POINT_UPLOAD_PATH);
            }
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory()) {
                System.out.println("上传目录不存在");
                logger.debug("上传目录不存在");
                file.mkdirs();
            } else {
                logger.debug("上传目录存在");
                System.out.println("上传目录存在");
            }
            // 生成文件
            OutputStream out = new FileOutputStream(file.getPath() + File.separator + fileName + ".dpl");
            out.write(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("exportToFile IOException \r{}", e);
        } finally {
            try {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
            }
        }
    }
    /**
     * 创建文件内容
     * @param list 数据
     * @param keys list中map的key数组集合
     * @throws IOException
     * @throws JsonProcessingException
     */
    public static String createFile(List<?> list) {
        ObjectMapper mapper = new ObjectMapper();
        StringBuffer data = new StringBuffer();
        JsonNode node;
        try {
            node = mapper.readTree(mapper.writeValueAsString(list));
            // 设置每行每列的值
            for (short i = 0; i < node.size(); i++) {
                if (node.get(i).get("type").asText().equals("mn")) {
                    data.append(node.get(i).get("code").asText() + ",\tReal\r\n");
                } else if (node.get(i).get("type").asText().equals("sz")) {
                    data.append(node.get(i).get("code").asText() + ",\tBool\r\n");
                }
            }
        } catch (JsonProcessingException e) {
            logger.error("createFile JsonProcessingException \r{}", e);
        } catch (IOException e) {
            logger.error("createFile IOException \r{}", e);
        }
        return data.toString();
    }
    /***
     * true:already in using false:not using
     * @param port
     */
    public static boolean isLoclePortUsing(int port) {
        boolean flag = true;
        try {
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }
    /***
     * true:已经在使用 false:没有使用
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    @SuppressWarnings("resource")
    public static boolean isPortUsing(String host, int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress theAddress = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(theAddress, port);
            socket.getPort();
            flag = true;
        } catch (IOException e) {
        }
        return flag;
    }
    /**
     * 两个时间之间相差距离多少天
     * @param one 时间参数 1：
     * @param two 时间参数 2：
     * @return 相差天数
     */
    public static long getDistanceDays(String str1, String str2) throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    public static long[] getDistanceTimes(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long[] times = { day, hour, min, sec };
        return times;
    }
    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @param type 时间格式 1 天时分秒 2 天时分 3 天时 4 天
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(long time1, long time2, int type) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        switch (type) {
            case 1:
                return day + "天" + hour + "小时" + min + "分" + sec + "秒";
            case 2:
                return day + "天" + hour + "小时" + min + "分";
            case 3:
                return day + "天" + hour + "小时";
            case 4:
                return day + "天";
            default:
                return day + "天" + hour + "小时" + min + "分" + sec + "秒";
        }
    }
    /**
     * convertSourData
     * @Description: string 转 double
     * @param @param dataStr
     * @param @return
     * @param @throws Exception 参数
     * @return double 返回类型
     */
    public static int convertInteger(String dataStr) {
        Integer value = 0;
        try {
            if (dataStr != null && !"".equals(dataStr)) {
                value = Integer.parseInt(dataStr);
            }
        } catch (Exception e) {
            value = -1;
        }
        return value;
    }
    /**
     * convertSourData
     * @Description: string 转 double
     * @param @param dataStr
     * @param @return
     * @param @throws Exception 参数
     * @return double 返回类型
     */
    public static long convertLong(String dataStr) {
        long value = 0;
        try {
            if (dataStr != null && !"".equals(dataStr)) {
                value = Long.parseLong(dataStr);
            }
        } catch (Exception e) {
            value = -1;
        }
        return value;
    }
    /**
     * 生成图像
     * @throws WriterException
     * @throws IOException
     */
    public static void generateQRCode(String filePath, String fileName, Map<String, Object> params, String content)
            throws WriterException, IOException {
        if (content == null) {
            content = JSON.toJSONString(params);// 内容
        }
        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        if (filePath == null) {
            Date nowDate = new Date();
            String cate = new SimpleDateFormat("yyyyMM").format(nowDate);
            // windows下
            if ("\\".equals(File.separator)) {
                filePath = WINDOWS_UPLOAD_IMG_PATH + File.separator + cate;
            }
            // linux下
            if ("/".equals(File.separator)) {
                filePath = LINUX_UPLOAD_IMG_PATH + File.separator + cate;
            }
            // windows下
            File file = new File(filePath);
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory()) {
                System.out.println("上传目录不存在");
                file.mkdirs();
            } else {
                System.out.println("上传目录存在");
            }
        }
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        Path path = FileSystems.getDefault().getPath(filePath, fileName + "." + format);
        System.out.println("bitMatrix \r\n" + bitMatrix);
        System.out.println("format \r\n" + format);
        System.out.println("path \r\n" + path);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
    }
    /**
     * @Title: sendMessage
     * @Description: TODO
     * @param alias
     * @param content
     * @param title 透传不支持title
     * @param description 0 通知 1消息使用透传方式
     * @param passThrough
     * @throws Exception
     * @return: void
     */
    public static void sendMessage(String[] alias, String content, String title, String description, int passThrough)
            throws Exception {
        Constants.useOfficial();
        Sender sender = new Sender(APP_MASTER_SECRET);
        List<TargetedMessage> messages = new ArrayList<TargetedMessage>();
        Message message = new Message.Builder().restrictedPackageName(APP_PACKAGE).title(title).description(description)
                .payload(content).passThrough(passThrough).notifyType(1) // 使用默认提示音提示
                .build();
        for (String user : alias) {
            TargetedMessage targetedMessage = new TargetedMessage();
            targetedMessage.setTarget(TargetedMessage.TARGET_TYPE_ALIAS, user);
            targetedMessage.setMessage(message);
            messages.add(targetedMessage);
        }
        Result rs = sender.send(messages, 0); // 根据regID，发送消息到指定设备上，不重试。
        System.out.println("MessageId" + rs.getMessageId());
        System.out.println("ErrorCode" + rs.getErrorCode().getValue());
    }
    public static void main(String[] a) throws Exception {
        // createEmchatGroup("程宁测试", "程宁测试", 100L, true, "yangbubin", null);
        // addEmchatBatchUsersToChatGroup("251747922738151860",null);
        /*
         * String[] taggers = new String[] { "257627531128078764" };
         * changeEmchatUserPwd("chengning123", "cn1234"); Map<String, String> ext = new HashMap<>();
         * ext.put("123", "123"); CommonUtils.sendEmchatMessage(CommonUtils.UPLOAD_TYPE_MSG_TEXT,
         * taggers, "ceshi", "fabuhui-test-10-18", ext, null);
         */
        // System.out.println(baiduVoiceRecognition("amr", "dasdsa", 3254,
        // "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"));
        System.out.println(CommonUtils.MD5("Cloudinnov@**2016"));
    }
    /**
     * 创建环信用户组.返回用户组ID
     * @Title: createEmchatGroup
     * @Description: TODO
     * @param groupName
     * @param desc
     * @param maxUsers
     * @param approval
     * @param owner
     * @param members
     * @return
     * @return: String
     */
    public static String createEmchatGroup(String groupName, String desc, Long maxUsers, Boolean approval, String owner,
            String[] members) {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        ChatGroupAPI group = (ChatGroupAPI) factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
        ChatGroupBody body = new ChatGroupBody(groupName, desc, false, maxUsers, approval, owner, members);
        ResponseWrapper response = (ResponseWrapper) group.createChatGroup(body);
        ObjectNode json = (ObjectNode) response.getResponseBody();
        String groupId = json.get("data").get("groupid").asText();
        return groupId;
    }
    /**
     * 创建环信用户组.返回状态码
     * @Title: createEmchatUser
     * @Description: TODO
     * @param userName
     * @param password
     * @param nickName
     * @return
     * @return: int
     */
    public static ResponseWrapper createEmchatUser(String userName, String password, String nickName) {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
        IMUserBody userBody = new IMUserBody(userName, password, nickName);
        ResponseWrapper response = (ResponseWrapper) user.createNewIMUserSingle(userBody);
        return response;
    }
    /**
     * 创建环信用户组.返回状态码
     * @Title: createEmchatUser
     * @Description: TODO
     * @param userName
     * @param password
     * @param nickName
     * @return
     * @return: int
     */
    public static ResponseWrapper changeEmchatUserPwd(String userName, String password) {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
        ResetPasswordBody userBody = new ResetPasswordBody(password);
        ResponseWrapper response = (ResponseWrapper) user.modifyIMUserPasswordWithAdminToken(userName, userBody);
        return response;
    }
    /**
     * 批量添加用户到环信用户组.返回状态码
     * @Title: addEmchatBatchUsersToChatGroup
     * @Description: TODO
     * @param groupId
     * @param members
     * @return
     * @return: ResponseWrapper
     */
    public static ResponseWrapper addEmchatBatchUsersToChatGroup(String groupId, String[] members) {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        ChatGroupAPI group = (ChatGroupAPI) factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
        UserNamesBody body = new UserNamesBody(members);
        ResponseWrapper response = (ResponseWrapper) group.addBatchUsersToChatGroup(groupId, body);
        return response;
    }
    /**
     * 添加用户到环信用户组.返回状态码
     * @Title: addEmchatBatchUsersToChatGroup
     * @Description: TODO
     * @param groupId
     * @param members
     * @return
     * @return: ResponseWrapper
     */
    public static ResponseWrapper addEmchatUserToChatGroup(String groupId, String member) {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        ChatGroupAPI group = (ChatGroupAPI) factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
        ResponseWrapper response = (ResponseWrapper) group.addSingleUserToChatGroup(groupId, member);
        return response;
    }
    public static ResponseWrapper sendEmchatMessage(int targetType, String[] targets, String msg, String fromUser,
            Map<String, String> ext, ImgMessageBody imgBody) throws JsonProcessingException {
        EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
                .getAPIFactory();
        SendMessageAPI sendMessageAPI = (SendMessageAPI) factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
        ResponseWrapper response = null;
        if (targetType == CommonUtils.UPLOAD_TYPE_MSG_TEXT) {
            TextMessageBody body = new TextMessageBody("chatgroups", targets, fromUser, ext, msg);
            response = (ResponseWrapper) sendMessageAPI.sendMessage(body);
        }
        if (targetType == CommonUtils.UPLOAD_TYPE_MSG_IMAGE) {
            ImgMessageBody body = new ImgMessageBody("chatgroups", targets, fromUser, null, imgBody.getUrl(),
                    imgBody.getFilename(), imgBody.getSecret(), imgBody.getWidth(), imgBody.getHeight());
            response = (ResponseWrapper) sendMessageAPI.sendMessage(body);
        }
        return response;
    }
    /**
     * 百度云语音识别
     * @Title: baiduVoiceRecognition
     * @Description: TODO
     * @param fileType
     * @param cuid
     * @param length
     * @param base64String
     * @return
     * @throws Exception
     * @return: List<String>
     */
    public static List<String> baiduVoiceRecognition(String fileType, String cuid, long length, String base64String)
            throws Exception {
        String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + "&client_id="
                + baiduApiKey + "&client_secret=" + baiduSecretKey;
        HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();
        String token = JSON.parseObject(printResponse(conn)).getString("access_token");
        conn = (HttpURLConnection) new URL(baiduServerURL).openConnection();
        JSONObject params = new JSONObject();
        params.put("format", fileType);
        params.put("rate", 8000);
        params.put("channel", "1");
        params.put("token", token);
        params.put("cuid", cuid);
        params.put("len", length);
        params.put("speech", base64String);
        // add request header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(params.toString());
        wr.flush();
        wr.close();
        List<String> urls = Collections.emptyList();
        ;
        if (conn.getResponseCode() != 200) {
            try {
                String str = JSON.parseObject(printResponse(conn)).getJSONArray("result").toJSONString();
                urls = JSON.parseArray(str, String.class);
            } catch (Exception e) {
                logger.error("baiduVoiceRecognition", e);
            }
        }
        conn.disconnect();
        return urls;
    }
    private static String printResponse(HttpURLConnection conn) throws Exception {
        if (conn.getResponseCode() != 200) {
            return "";
        }
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    }
    /***
     * @param date
     * @param dateFormat : e.g:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String formatDateByPattern(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.CHINESE);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
    public static String getCronByDate(long time) {
        String dateFormat = "ss mm HH dd MM ? yyyy";
        return formatDateByPattern(new Date(time), dateFormat);
    }
    /**
     * 中文数字转阿拉伯数组【十万九千零六十 --> 109060】
     * @author ningcheng
     * @param chineseNumber
     * @return
     */
    public static int chineseNumber2Int(String chineseNumber) {
        int result = 0;
        int temp = 1;// 存放一个单位的数字如：十万
        int count = 0;// 判断是否有chArr
        char[] cnArr = new char[] { '一', '二', '三', '四', '五', '六', '七', '八', '九' };
        char[] chArr = new char[] { '十', '百', '千', '万', '亿' };
        for (int i = 0; i < chineseNumber.length(); i++) {
            boolean b = true;// 判断是否是chArr
            char c = chineseNumber.charAt(i);
            for (int j = 0; j < cnArr.length; j++) {// 非单位，即数字
                if (c == cnArr[j]) {
                    if (0 != count) {// 添加下一个单位之前，先把上一个单位值添加到结果中
                        result += temp;
                        temp = 1;
                        count = 0;
                    }
                    // 下标+1，就是对应的值
                    temp = j + 1;
                    b = false;
                    break;
                }
            }
            if (b) {// 单位{'十','百','千','万','亿'}
                for (int j = 0; j < chArr.length; j++) {
                    if (c == chArr[j]) {
                        switch (j) {
                            case 0:
                                temp *= 10;
                                break;
                            case 1:
                                temp *= 100;
                                break;
                            case 2:
                                temp *= 1000;
                                break;
                            case 3:
                                temp *= 10000;
                                break;
                            case 4:
                                temp *= 100000000;
                                break;
                            default:
                                break;
                        }
                        count++;
                    }
                }
            }
            if (i == chineseNumber.length() - 1) {// 遍历到最后一个字符
                result += temp;
            }
        }
        return result;
    }
    public static String parseToColor(String c) {
        String color = null;
        int red = Integer.parseInt(c.substring(0, 3));
        int green = Integer.parseInt(c.substring(3, 6));
        int yellow = Integer.parseInt(c.substring(0, 3)) + Integer.parseInt(c.substring(3, 6));
        if (red == 255 && green == 0) {
            color = "red";
        } else if (green == 255 && red == 0) {
            color = "green";
        } else if (yellow == 510) {
            color = "yellow";
        }
        return color;
    }
    public static double calculationVI(float value) {
       /* double countValue = 0;
        if (value == 0) {
            return 0;
        }
        countValue = 2.99 * 100000 / (value * 2500 / 16000);
        return countValue;*/
    	return value;
    }
    public static void writeStringToFile(String filePath, String data) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(filePath, true);
            bw = new BufferedWriter(fw);
            bw.append(data);
        } catch (IOException e) {
            logger.error("文件写入异常, e: {}", e);
            e.printStackTrace();
        }  finally {
            try {
                bw.close();
                fw.close();
            } catch (IOException e) {
                logger.error("关闭文件流失败, e: {}", e);
                e.printStackTrace();
            }
            
        }
    }
}
